<template>
  <div class="cart-container">
    <!-- 顶部导航 -->
    <TopNav />
    <div class="cart-header">
      <a href="./">
        <img class="logo" src="../../assets/imgs/search/jd_logo.png" alt="京东logo" />
      </a>
      <h1>购物车({{ authStore.isLoggedIn ? cartStore.totalCount : 0 }})</h1>

      <!-- 添加搜索功能 -->
      <div class="cart-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索购物车商品"
          class="search-input"
          clearable
        >
          <template #append>
            <el-button @click="searchItems">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <div v-if="!authStore.isLoggedIn" class="empty-cart">
      <div class="empty-icon">🔒</div>
      <p>登录后查看购物车中的商品</p>
      <el-button type="primary" @click="$router.push('/login')">去登录</el-button>
    </div>
    <template v-else>
      <div v-if="cartStore.items.length === 0" class="empty-cart">
        <div class="empty-icon">🛒</div>
        <p>购物车还是空的</p>
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </div>

      <div v-else class="cart-layout">
        <!-- 调试信息 - 开发模式下显示 -->

        <!-- 左侧购物车内容 -->
        <div class="cart-content">
          <!-- 购物车头部操作栏 -->
          <div class="cart-toolbar">
            <div class="select-all">
              <el-checkbox
                :model-value="cartStore.isAllSelected"
                @change="cartStore.toggleAllSelection"
              >
                全选
              </el-checkbox>
            </div>
            <div class="toolbar-actions">
              <el-button
                type="danger"
                size="small"
                @click="cartStore.clearSelected"
                :disabled="cartStore.selectedCount === 0"
              >
                删除
              </el-button>
              <el-button type="primary" size="small" :disabled="cartStore.selectedCount === 0">
                移入收藏
              </el-button>
              <el-button type="warning" size="small" @click="cartStore.clearCart">
                清空购物车
              </el-button>
              <el-button type="success" size="small"> 降价提醒 </el-button>
              <div class="delivery-location">
                配送至：
                <el-dropdown>
                  <span class="el-dropdown-link">
                    河北廊坊市
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>北京市</el-dropdown-item>
                      <el-dropdown-item>上海市</el-dropdown-item>
                      <el-dropdown-item>广州市</el-dropdown-item>
                      <el-dropdown-item>深圳市</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 购物车商品列表 -->
          <div class="cart-items">
            <div v-for="item in filteredItems" :key="item.id" class="cart-item">
              <div class="item-select">
                <el-checkbox
                  :model-value="item.selected"
                  @change="() => cartStore.toggleItemSelection(item.id)"
                />
              </div>

              <div class="item-image">
                <img
                  v-if="item.image"
                  :src="getSafeImagePath(item)"
                  :alt="item.title || '商品图片'"
                  @error="handleImageError"
                  @load="handleImageLoad"
                  :class="{ 'image-loaded': item.imageLoaded }"
                />
                <!-- 图片加载失败时显示默认图片 -->
                <div
                  v-if="!item.image || (!item.imageLoaded && item.imageError)"
                  class="image-placeholder"
                >
                  <span>🖼️</span>
                  <p>图片加载失败</p>
                </div>
                <!-- 没有图片时显示默认占位符 -->
                <div v-if="!item.image && !item.imageError" class="image-placeholder">
                  <span>📦</span>
                  <p>暂无图片</p>
                </div>
              </div>

              <div class="item-info">
                <h3 class="item-title">{{ item.title || '商品名称' }}</h3>
                <div class="item-tags">
                  <span v-if="item.cityType" class="tag city-type">{{ item.cityType }}</span>
                  <span v-if="item.fromType" class="tag from-type">{{ item.fromType }}</span>
                </div>
              </div>

              <div class="item-price">
                <span class="price">￥{{ item.price || '0.00' }}</span>
              </div>

              <div class="item-quantity">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="99"
                  size="small"
                  @change="(value) => cartStore.updateQuantity(item.id, value)"
                />
              </div>

              <div class="item-total">
                <span class="total-price">￥{{ calculateItemTotal(item) }}</span>
              </div>

              <div class="item-actions">
                <el-button type="danger" size="small" @click="cartStore.removeItem(item.id)">
                  删除
                </el-button>
              </div>
            </div>
          </div>

          <!-- 购物车底部结算栏 -->
          <div class="cart-footer">
            <div class="footer-left">
              <el-checkbox
                :model-value="cartStore.isAllSelected"
                @change="cartStore.toggleAllSelection"
              >
                全选
              </el-checkbox>
              <span class="selected-info"> 已选择 {{ cartStore.selectedCount }} 件商品 </span>
            </div>

            <div class="footer-right">
              <div class="total-info">
                <span>合计：</span>
                <span class="total-price">￥{{ cartStore.totalPrice }}</span>
              </div>
              <el-button
                type="danger"
                size="large"
                @click="handleCheckout"
                :disabled="cartStore.selectedCount === 0"
              >
                结算 ({{ cartStore.selectedCount }})
              </el-button>
            </div>
          </div>
        </div>
        <div class="checkout-detail">
          <div class="detail-header">
            <h3>结算明细</h3>
          </div>
          <div class="detail-content">
            <div class="selected-products">
              <div class="product-count">
                <span>已选商品</span>
                <span class="count">{{ cartStore.selectedCount }}件</span>
              </div>
              <div class="empty-cart-icon" v-if="cartStore.selectedCount === 0">
                <div class="icon">🛒</div>
                <p>选择商品后查看详情</p>
              </div>
              <div class="selected-list" v-else>
                <div
                  v-for="item in cartStore.items.filter((i) => i.selected)"
                  :key="item.id"
                  class="selected-item"
                >
                  <div class="item-name">{{ item.title || '商品名称' }}</div>
                  <div class="item-subtotal">￥{{ calculateItemTotal(item) }}</div>
                </div>
              </div>
            </div>
            <div class="detail-divider"></div>
            <div class="detail-item">
              <span>商品金额：</span>
              <span>￥{{ cartStore.totalPrice }}</span>
            </div>
            <div class="detail-item">
              <span>优惠金额：</span>
              <span class="discount">￥0.00</span>
            </div>
            <div class="detail-item">
              <span>运费：</span>
              <span class="shipping">￥0.00</span>
            </div>
            <div class="detail-divider"></div>
            <div class="detail-item total">
              <span>应付总额：</span>
              <span class="total-amount">￥{{ cartStore.totalPrice }}</span>
            </div>
          </div>
          <div class="detail-footer">
            <el-button
              type="danger"
              size="large"
              @click="handleCheckout"
              :disabled="cartStore.selectedCount === 0"
              class="checkout-btn"
            >
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useCartStore } from '@/stores/cart'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import TopNav from '../home/components/TopNav.vue'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import router from '@/router'

const cartStore = useCartStore()
const authStore = useAuthStore()
authStore.initialize()

// 在组件挂载时初始化购物车数据
onMounted(() => {
  cartStore.initializeItems()
})

const searchKeyword = ref('')

// 过滤购物车商品
const filteredItems = computed(() => {
  if (!searchKeyword.value) {
    return cartStore.items
  }
  return cartStore.items.filter(
    (item) => item.title && item.title.toLowerCase().includes(searchKeyword.value.toLowerCase()),
  )
})

// 搜索功能
const searchItems = () => {
  if (filteredItems.value.length === 0 && searchKeyword.value) {
    ElMessage.info('没有找到匹配的商品')
  }
}

// 图片加载错误处理
const handleImageError = (event) => {
  // 通过事件目标找到对应的商品项
  const imgElement = event.target
  const itemTitle = imgElement.alt

  // 查找对应的购物车项
  const item = cartStore.items.find((item) => item.title === itemTitle)
  if (item) {
    item.imageError = true
    item.imageLoaded = false
  }
}

// 图片加载成功处理
const handleImageLoad = (event) => {
  // 通过事件目标找到对应的商品项
  const imgElement = event.target
  const itemTitle = imgElement.alt

  // 查找对应的购物车项
  const item = cartStore.items.find((item) => item.title === itemTitle)
  if (item) {
    item.imageLoaded = true
    item.imageError = false
  }
}

// 获取安全的图片路径
const getSafeImagePath = (item) => {
  if (!item.image) return ''

  // 如果是完整的 URL，直接返回
  if (item.image.startsWith('http') || item.image.startsWith('data:')) {
    return item.image
  }

  // 如果是相对路径，尝试转换为绝对路径
  try {
    // 如果是相对路径，尝试添加基础路径
    if (item.image.startsWith('/')) {
      return item.image
    } else {
      // 处理相对路径
      return '/' + item.image
    }
  } catch {
    return item.image
  }
}

// 计算单项商品总价
const calculateItemTotal = (item) => {
  const price = parseFloat(item.price) || 0
  const quantity = parseInt(item.quantity) || 0
  return (price * quantity).toFixed(2)
}

// 结算功能
const handleCheckout = () => {
  if (cartStore.selectedCount === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  ElMessage.success(`正在结算 ${cartStore.selectedCount} 件商品，总价：￥${cartStore.totalPrice}`)
  // 这里可以添加跳转到结算页面的逻辑
  router.push('/payorder')
}
</script>

<style lang="scss" scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}

.cart-header {
  display: flex;
  align-items: center;
  padding: 20px 0;
  margin-bottom: 20px;

  a {
    img {
      width: 176px;
      height: 44px;
    }
  }

  h1 {
    color: rgb(136, 139, 148);
    margin: 0 auto 0 20px;
  }

  .cart-search {
    margin-left: auto;
    width: 300px;

    .search-input {
      width: 100%;
    }
  }
}

.empty-cart {
  text-align: center;
  padding: 100px 0;

  .empty-icon {
    font-size: 80px;
    margin-bottom: 20px;
  }

  p {
    color: #999;
    margin-bottom: 30px;
  }
}

// 添加左右布局
.cart-layout {
  display: flex;
  gap: 20px;

  .cart-content {
    flex: 1;
  }

  // 更新右侧结算明细样式，模仿图片
  .checkout-detail {
    width: 300px;
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    height: fit-content;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #f0f0f0;

    .detail-header {
      border-bottom: 1px solid #f0f0f0;
      padding-bottom: 10px;
      margin-bottom: 15px;

      h3 {
        margin: 0;
        color: #333;
        font-size: 16px;
        font-weight: bold;
      }
    }

    .detail-content {
      .selected-products {
        margin-bottom: 15px;

        .product-count {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          font-size: 14px;
          color: #666;

          .count {
            color: #e4393c;
          }
        }

        .empty-cart-icon {
          text-align: center;
          padding: 20px 0;

          .icon {
            font-size: 40px;
            margin-bottom: 10px;
            color: #ccc;
          }

          p {
            color: #999;
            font-size: 12px;
          }
        }

        .selected-list {
          max-height: 150px;
          overflow-y: auto;

          .selected-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 12px;

            .item-name {
              flex: 1;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              color: #666;
            }

            .item-subtotal {
              color: #e4393c;
              margin-left: 10px;
            }
          }
        }
      }

      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        font-size: 14px;
        color: #666;

        .discount,
        .shipping {
          color: #67c23a;
        }

        &.total {
          font-weight: bold;
          color: #333;
          font-size: 16px;

          .total-amount {
            color: #e4393c;
            font-size: 20px;
          }
        }
      }

      .detail-divider {
        height: 1px;
        background: #f0f0f0;
        margin: 15px 0;
      }
    }

    .detail-footer {
      margin-top: 20px;

      .checkout-btn {
        width: 100%;
        border-radius: 20px;
        font-size: 16px;
        height: 40px;
        background: #e4393c;
        border-color: #e4393c;

        &:hover {
          background: #c1272d;
          border-color: #c1272d;
        }

        &:disabled {
          background: #f8f8f8;
          color: #999;
          border-color: #e0e0e0;
        }
      }
    }
  }
}

.cart-content {
  .cart-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: #f8f8f8;
    border-radius: 8px;
    margin-bottom: 20px;

    .toolbar-actions {
      display: flex;
      align-items: center;

      .el-button {
        margin-left: 10px;
      }

      .delivery-location {
        margin-left: 15px;
        font-size: 14px;
        color: #666;
        display: flex;
        align-items: center;

        .el-dropdown-link {
          color: #e4393c;
          cursor: pointer;
          display: flex;
          align-items: center;
        }
      }
    }
  }

  .cart-items {
    .cart-item {
      display: flex;
      align-items: center;
      padding: 20px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      margin-bottom: 15px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      .item-select {
        width: 60px;
        text-align: center;
      }

      .item-image {
        width: 100px;
        height: 100px;
        margin-right: 20px;
        position: relative;
        /* Added for positioning placeholder */

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 4px;
          display: block;
          /* Ensure no extra space below image */
        }

        .image-placeholder {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: #f0f0f0;
          border-radius: 4px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          color: #999;
          font-size: 24px;
          z-index: 1;

          p {
            margin-top: 5px;
            font-size: 12px;
          }
        }
      }

      .item-info {
        flex: 1;
        margin-right: 20px;

        .item-title {
          font-size: 16px;
          color: #333;
          margin: 0 0 10px 0;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .item-tags {
          .tag {
            display: inline-block;
            padding: 2px 8px;
            margin-right: 10px;
            border-radius: 4px;
            font-size: 12px;

            &.city-type {
              color: #e4393c;
              border: 1px solid lightcoral;
              background: #fff0f0;
            }

            &.from-type {
              color: rgb(76, 200, 161);
              border: 1px solid rgb(76, 200, 161);
              background: #f0f9f6;
            }
          }
        }
      }

      .item-price {
        width: 120px;
        text-align: center;

        .price {
          color: #e4393c;
          font-size: 18px;
          font-weight: bold;
        }
      }

      .item-quantity {
        width: 120px;
        text-align: center;
      }

      .item-total {
        width: 120px;
        text-align: center;

        .total-price {
          color: #e4393c;
          font-size: 18px;
          font-weight: bold;
        }
      }

      .item-actions {
        width: 80px;
        text-align: center;
      }
    }
  }

  .cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: #f8f8f8;
    border-radius: 8px;
    margin-top: 20px;

    .footer-left {
      display: flex;
      align-items: center;

      .selected-info {
        margin-left: 20px;
        color: #666;
      }
    }

    .footer-right {
      display: flex;
      align-items: center;

      .total-info {
        margin-right: 20px;
        font-size: 16px;

        .total-price {
          color: #e4393c;
          font-size: 24px;
          font-weight: bold;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 992px) {
  .cart-layout {
    flex-direction: column;

    .checkout-detail {
      width: 100%;
      margin-top: 20px;
    }
  }
}

// 调试信息样式

@media (max-width: 768px) {
  .cart-container {
    padding: 10px;
  }

  .cart-header {
    flex-direction: column;
    align-items: flex-start;

    h1 {
      margin: 10px 0;
    }

    .cart-search {
      width: 100%;
      margin-top: 10px;
    }
  }

  .cart-item {
    flex-direction: column;
    text-align: center;

    .item-image {
      margin: 0 0 15px 0;
    }

    .item-info {
      margin: 0 0 15px 0;
    }

    .item-price,
    .item-quantity,
    .item-total {
      margin: 10px 0;
    }
  }

  .cart-footer {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>
